package com.chart.common.utils.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
/**
 * 对excel操作的工具类
 *
 * @author 罗继全
 * 2024/6/30 18:55
 */


public class ExcelExportUtils {

    public static void exportExcel(List<Map<String, Object>> dataList, String filePath) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // Write data excluding the first row
        int rowIdx = 0;
        for (Map<String, Object> data : dataList) {
            Row row = sheet.createRow(rowIdx++);
            int colIdx = 0;
            for (String key : data.keySet()) {
                Cell cell = row.createCell(colIdx++);
                Object value = data.get(key);
                if (value != null) {
                    cell.setCellValue(value.toString());
                }
            }
        }

        // Resize columns (optional)
        for (int i = 0; i < dataList.get(0).keySet().size(); i++) {
            sheet.autoSizeColumn(i);
        }

        // Write the workbook to the file system
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            workbook.write(fos);
        }
        workbook.close();
    }

    public static void exportCsvFile(List<Map<String, Object>> dataList, String filePath) throws IOException {
        try (PrintWriter writer = new PrintWriter(new File(filePath))) {
            StringBuilder sb = new StringBuilder();

            // Skip the first row if it exists
            boolean firstRowSkipped = false;
            for (Map<String, Object> data : dataList) {
                if (!firstRowSkipped) {
                    firstRowSkipped = true;
                    continue;
                }
                for (Object value : data.values()) {
                    sb.append(value).append(",");
                }
                sb.deleteCharAt(sb.length() - 1);
                sb.append("\n");
            }

            writer.write(sb.toString());
        }
    }
}
